package com.matrix.draft.jvm.gc;

import com.matrix.draft.jvm.util.ByteSize;
import lombok.SneakyThrows;

import java.lang.ref.*;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.IntStream;

/**
 * 测试jvm的四种应用类型
 * 强引用 (Strong Reference) 不回收
 * 弱引用 (Soft Reference) 内存满时回收
 * 虚引用 (Weak Reference) 遇到GC时回收
 * 幽灵引用 (Phantom Reference)
 */
public class TestRef {

    public static void main(String[] args) {
        weakRef();
    }




    // 强引用
    static void strongRef() {
        Object obj = new Object();
    }




    // 弱引用(外界常称软引用)
    @SneakyThrows
    static void softRef() {
        List<SoftReference<byte[]>> list = new LinkedList<>();
        ReferenceQueue queue = new ReferenceQueue();
        IntStream.range(0, 50).forEach(i -> {
            list.add(new SoftReference<>(new byte[ByteSize.SIZE_1M], queue));
        });
        // 从list中移除掉存在于队列中的Reference对象
        Reference poll;
        while ((poll = queue.poll()) != null) list.remove(poll);
        // 输出
        list.forEach(ref -> {
            System.err.println(ref.get());
        });
    }
    // 虚引用(外界常称弱引用)
    static void weakRef() {
        List<WeakReference<byte[]>> list = new LinkedList<>();
        ReferenceQueue queue = new ReferenceQueue();
        IntStream.range(0, 8).forEach(i -> {
            WeakReference ref = new WeakReference<>(new byte[ByteSize.SIZE_1M], queue);
            list.add(ref);
            list.forEach(r->{
                System.out.print(r.get());
                System.out.print(",");
            });
            System.out.println();
        });
    }
    // 幽灵引用(外界常称虚引用)
    static void phantomRef() {
        PhantomReference<Object> obj = new PhantomReference(new Object(), new ReferenceQueue());
    }

}
